package com.design.pattern.prototype.deep;

import lombok.Data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @author: CRM_SYSTEM
 * @date: 2022/9/15 23:34
 * @Description:
 */
@Data
public class User implements Cloneable,Serializable{

    private String name;
    private String gender;
    private Integer age;
    private double weight;
    private List<String> hobbies;


    @Override
    public User clone() throws CloneNotSupportedException {
        return (User)super.clone();
    }


    public User deepClone()  {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (User)ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public User deepCloneV2(){
        try {
            User user =(User) super.clone();
            user.hobbies=(List)((ArrayList)user.hobbies).clone();
            return user;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", weight=" + weight +
                ", hobbies=" + hobbies +
                '}';
    }
}
